package org.geektimes.configuration.micro.config.source.servlet;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.configuration.micro.config.DefaultConfigProviderResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.logging.Logger;

public class ServletContxtConfitSourceListener implements ServletContextListener {
    private static final Logger logger = Logger.getLogger(ServletContxtConfitSourceListener.class.getName());
    public static final String CONTEXT_NAME = Config.class.getName();


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("ServletContxtConfitSourceListener");
        ServletContext servletContext = sce.getServletContext();
        ConfigProviderResolver configProviderResolver = DefaultConfigProviderResolver.instance();
        ClassLoader classLoader = servletContext.getClassLoader();
        Config config = configProviderResolver.getBuilder()
                //配置默认默认ClassLoader
                .forClassLoader(classLoader)
                //默认配置源
                .addDefaultSources()
                //发现配置源
                .addDiscoveredSources()
                //自定义配置源
                .withSources(new ServletConfigSource(servletContext))
                //发现转换器
                .addDiscoveredConverters()
                .build();
        configProviderResolver.registerConfig(config, classLoader);
        servletContext.setAttribute(CONTEXT_NAME, config);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
